<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Plugin for setting up session if remember me cookie is found.
 */
class RedCross_Controller_Plugin_RememberMe extends Zend_Controller_Plugin_Abstract
{
	public function routeShutdown(Zend_Controller_Request_Abstract $req)
	{
		$auth = RedCross_Factory::getService('Core_Service_Auth');
		if ($auth->isAuthenticated())
			return;

		if (!($req instanceof Zend_Controller_Request_Http))
			return;

		$remcook = $req->getCookie('rememberme');
		if ($remcook === null)
			return;
		
		$arr = split(':', $remcook);
		$userval = new RedCross_Validate_Username();
		$cookieval = new Zend_Validate_Regex('/[a-f0-9]{40}/');
		if (!$userval->isValid($arr[0]) || !$cookieval->isValid($arr[1]))
			return;

		$username = $arr[0];
		$cookie = $arr[1];

		$auth->authenticate($username, $cookie, true);
		$acl = Zend_Registry::get('acl');
		$acl->initRole();
        Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($acl->retrieveRole());
	}
}